using UnityEngine;
using System.Collections;

/// \class  gkSpawningRandomAltitudeInGame
/// \brief  Select randomly an altitude that is in the game volume
[AddComponentMenu("GK/Engine/Game/Spawn/gkSpawningRandomAltitudeInGame")]
public class gkSpawningRandomAltitudeInGame : gkSpawningModifier
{
    /// The minimum drop altitude in screen percent
    public float DropAltitudePercentMin = 0.0f;

    /// The maximum drop altitude in screen percent
    public float DropAltitudePercentMax = 1.0f;

    /// The game volume bounding box
    private Bounds m_oGameVolumeBoudingBox;

    /// \brief  Called just after the game begin to play
    void Start()
    {
	   // Get the spawning volume bounding box
	   gkUtilityBounds.GrabColliderOrRendererBounds(GameObject.Find("GameVolume"), out m_oGameVolumeBoudingBox);
    }

    /// \brief  Event called at the and of the actor spawn
    public override void ModifySpawnedActor(GameObject a_rSpawnedActor, int a_iNumActorsInCurrentBatch, int a_iNbActorsInCurrentBatch)
    {
	    RandomAltitude(a_rSpawnedActor);
    }

    /// \brief  Select randomly an altitude that is in the game volume
    void RandomAltitude(GameObject a_rSpawnedActor)
    {
	    Vector3 f3SpawnedPosition;
	    float fVolumeHeight;
	    float fActorHalfHeight;
	    float fMinPositionY;
	    float fMaxPositionY;
		Bounds rSpawnedActorBounds;
		
		// Grab the spawned actor bounds
		 gkUtilityBounds.GrabRendererOrColliderBounds(a_rSpawnedActor, out rSpawnedActorBounds);

	    // Get the current position
	    f3SpawnedPosition = a_rSpawnedActor.transform.position;
    	
	    // Compute the min and max position
	    fVolumeHeight = m_oGameVolumeBoudingBox.max.y - m_oGameVolumeBoudingBox.min.y;
	    fActorHalfHeight = rSpawnedActorBounds.extents.y;
	    fMinPositionY = m_oGameVolumeBoudingBox.min.y + fVolumeHeight * DropAltitudePercentMin + fActorHalfHeight;
	    fMaxPositionY = m_oGameVolumeBoudingBox.min.y + fVolumeHeight * DropAltitudePercentMax - fActorHalfHeight;

	    // Choose a random abscissa to drop the object between the min and max position
	    f3SpawnedPosition.y = Random.Range(fMinPositionY, fMaxPositionY);

	    // Set the new position
	    a_rSpawnedActor.transform.position = f3SpawnedPosition;
    }
}
